<?php

namespace App\Http\Controllers\Tenant;

use DB;
use Validator;
use Illuminate\Http\Request;
use App\Customize\PddRequest;
use App\Models\QingShanERP\Shop;
use App\Http\Controllers\Controller;
use App\Models\QingShanERP\Logistics;

class LogisticsController extends Controller
{
    public function getList(Request $request)
    {
        try {
            $page = $request->input('page', 0);
            $size = $request->input('size', 10);
            $type = $request->input('type', 0);
            $shop_id = $request->input('shop_id', 0);
            $key = $request->input('key', '');
            $tenant_id = $request->tenant->tid;
            $list = Logistics::where('tenant_id', $tenant_id)->where(function ($q) use ($type) {
                if ($type != 0) {
                    $q->where('type', $type);
                }
            })->where(function ($q) use ($shop_id) {
                if ($shop_id != 0) {
                    $q->where('shop_id', $shop_id);
                }
            })->where(function ($q) use ($key) {
                if ($key != '') {
                    $q->where('logistics_company', 'like', '%' . $key . '%');
                }
            })->where('del_flag', 0)->offset(($page - 1) * $size)->limit($size)->orderBy('id', 'desc')->get();
            $count = Logistics::where('tenant_id', $tenant_id)->where(function ($q) use ($type) {
                if ($type != 0) {
                    $q->where('type', $type);
                }
            })->where(function ($q) use ($shop_id) {
                if ($shop_id != 0) {
                    $q->where('shop_id', $shop_id);
                }
            })->where(function ($q) use ($key) {
                if ($key != '') {
                    $q->where('logistics_company', 'like', '%' . $key . '%');
                }
            })->where('del_flag', 0)->count();
            $res = ['list' => $list, 'total' => $count];
            return $this->resData(200, '获取数据成功...', $res);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取数据失败，请稍后再试...');
        }
    }
    // 同步拼多多物流信息，出来的太多了，其实没有用
    public function postSyncPdd()
    {
        try {
            $result = PddRequest::request('pdd.logistics.companies.get');
            if (isset($result['logistics_companies_get_response'])) {
                $insert = [];
                $date = date('Y-m-d H:i:s');
                foreach ($result['logistics_companies_get_response']['logistics_companies'] as $v) {
                    if ($v['available']) {
                        $insert[] = ['type' => 4, 'logistics_company' => $v['logistics_company'], 'logistics_id' => $v['id'], 'logistics_code' => $v['code'], 'last_at' => $date, 'created_at' => $date, 'updated_at' => $date];
                    }
                }
                return $this->resData(200, '同步数据成功...', $insert);
            } else {
                return $this->resData(400, '请求快递公司信息失败...' . $result['error_response']['error_msg']);
            }
        } catch (\Throwable $e) {
            return $this->resData(500, '获取数据失败，请稍后再试...' . $e->getMessage());
        }
    }

    // 查所有拼多多的电子面单信息，方便记录下发货信息
    public function postSyncWaywill(Request $request){
        try {
            $s = Shop::where('type', 4)->where('del_flag', 0)->where('id', $request->input('shop_id'))->first();
            $params['access_token'] = $s->access_token;
            $params['timestamp'] = strval(time());
            $params['client_id'] = config('pdd.client_id');
            $result = PddRequest::request('pdd.waybill.search', $params);
            if (isset($result['pdd_waybill_search_response'])) {
                $list = [];
                foreach ($result['pdd_waybill_search_response']['waybill_apply_subscription_cols'] as $v) {
                    $list[] = ['wp_code' => $v['wp_code'], 'city' => $v['branch_account_cols'][0]['shipp_address_cols'][0]['city'], 'country' => $v['branch_account_cols'][0]['shipp_address_cols'][0]['country'], 'detail' => $v['branch_account_cols'][0]['shipp_address_cols'][0]['detail'], 'district' => $v['branch_account_cols'][0]['shipp_address_cols'][0]['district'], 'province' => $v['branch_account_cols'][0]['shipp_address_cols'][0]['province']];
                }
                return $this->resData(200, '同步数据成功...', $list);
            } else {
                return $this->resData(400, '请求面单信息失败...' . $result['error_response']['error_msg']);
            }
        } catch (\Throwable $e) {
            return $this->resData(500, '获取数据失败，请稍后再试...' . $e->getMessage());
        }
    }
    public function postSyncTemp(Request $request)
    {
        try {
            $s = Shop::where('type', 4)->where('del_flag', 0)->where('id', $request->input('shop_id'))->first();
            $params['access_token'] = $s->access_token;
            $params['timestamp'] = strval(time());
            $params['client_id'] = config('pdd.client_id');
            $result = PddRequest::request('pdd.cloudprint.stdtemplates.get', $params);
            if (isset($result['pdd_cloudprint_stdtemplates_get_response'])) {
                $list = [];
                foreach ($result['pdd_cloudprint_stdtemplates_get_response']['result']['datas'] as $v) {
                    $list[] = ['wp_code' => $v['wp_code'], 'standard_templates' => $v['standard_templates']];
                }
                return $this->resData(200, '同步面单模板数据成功...', $list);
            } else {
                return $this->resData(400, '请求面单模板信息失败...' . $result['error_response']['error_msg']);
            }
        } catch (\Throwable $e) {
            return $this->resData(500, '获取数据失败，请稍后再试...' . $e->getMessage());
        }
    }

    public function postCreate(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'type' => 'required|in:1,2,3,4',
                'logistics_company' => 'required|max:20',
                'logistics_id' => 'required|max:100',
                'logistics_code' => 'required|max:100',
            ]);
            $attrs = array(
                'type' => '类型',
                'logistics_company' => '公司名称',
                'logistics_id' => '公司编码',
                'logistics_code' => '公司代码'
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            $create = ['tenant_id'=>$request->tenant->tid, 'shop_id' => $all['shop_id'],'type' => $all['type'], 'logistics_company' => $all['logistics_company'], 'logistics_id' => $all['logistics_id'], 'logistics_code' => $all['logistics_code'], 'standard_template_name' => $all['standard_template_name'], 'standard_template_url' => $all['standard_template_url'], 'country' => $all['country'], 'province' => $all['province'], 'city' => $all['city'], 'district' => $all['district'], 'detail' => $all['detail']];
            Logistics::create($create);
            return $this->resData(200, '添加成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '添加文章失败，请重新操作...');
        }
    }
    //详情
    public function postDetail(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'logistics_id' => 'required|integer',
            ]);
            $attrs = array(
                'logistics_id' => '公司ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $id = $request->input('logistics_id');
            $info = Logistics::find($id);
            return $this->resData(200, '获取数据成功...', $info);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取数据失败，请重新操作...');
        }
    }
    //编辑
    public function postEdit(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'l_id' => 'required|integer',
                'type' => 'required|in:1,2,3,4',
                'logistics_company' => 'required|max:20',
                'logistics_id' => 'required|max:100',
                'logistics_code' => 'required|max:100',
            ]);
            $attrs = array(
                'l_id' => '公司ID',
                'type' => '类型',
                'logistics_company' => '公司名称',
                'logistics_id' => '公司编码',
                'logistics_code' => '公司代码'
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $id = $request->input('l_id');
            $all = $request->all();
            $update = ['type' => $all['type'],'logistics_company' => $all['logistics_company'], 'logistics_id' => $all['logistics_id'], 'logistics_code' => $all['logistics_code'], 'standard_template_name' => $all['standard_template_name'], 'standard_template_url' => $all['standard_template_url'], 'country' => $all['country'], 'province' => $all['province'], 'city' => $all['city'], 'district' => $all['district'], 'detail' => $all['detail']];
            Logistics::where('id', $id)->update($update);
            return $this->resData(200, '编辑成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '编辑失败，请重新操作...');
        }
    }

    //删除
    public function postRemove(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'logistics_id' => 'required|array',
            ]);
            $attrs = array(
                'logistics_id' => '公司ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $id = $request->input('logistics_id');
            Logistics::whereIn('id', $id)->where('tenant_id',$request->tenant->tid)->update(['del_flag' => 1]);
            return $this->resData(200, '删除成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '删除失败，请重新操作...');
        }
    }
}
